﻿using ODS.Config;
using ODS.Model;
using ODS.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ODS.WebService.Registry
{
    public class RetrieveEventTypeRegistryService
    {
        public static async Task<InfoResult> retrieveEventTypeRegistry()
        {
            String url = Constants.SERVER_URL + "/registry/eventType";

            InfoResult result;
            try
            {
                Stream xmlStream = await RESTfulService.HTTPGetRequest(url);
                List<EventTypeModel> eventType = ParseXML(xmlStream);

                result = new InfoResult(null, eventType);
            }
            catch (Exception ex)
            {
                result = new InfoResult(ex.Message, null);
            }

            return result;
        }

        private static List<EventTypeModel> ParseXML(Stream xmlStream)
        {
            List<EventTypeModel> listEventTypeModel = new List<EventTypeModel>();
            XDocument doc = XDocument.Load(xmlStream);

            var eventTypes = from eventType in doc.Descendants("registeredValue")
                            select new
                            {
                                Code = eventType.Element("code").Value,
                                Name = eventType.Element("name").Value,
                                Mnemonics = eventType.Element("mnemonics").Value,
                            };
            foreach (var eventType in eventTypes)
            {
                EventTypeModel eventTypeModel = new EventTypeModel();
                eventTypeModel.Name = eventType.Name;
                eventTypeModel.Code = eventType.Code;
                eventTypeModel.Mnemonics = eventType.Mnemonics;

                listEventTypeModel.Add(eventTypeModel);
            }


            return listEventTypeModel;

        }
    }
}
